#include "ParserSort.h"

const string ParserSort::regexInstructionAndArguments = "\\s*([a-zA-Z]+)\\s*(.*)";
const string ParserSort::regexArgumentSortAlphabet = "\\s*(a)\\s*";
const string ParserSort::regexArgumentSortCompleted = "\\s*(d)\\s*";
const string ParserSort::regexArgumentSortTime = "\\s*(t)\\s*";
const string ParserSort::regexArgumentSortFlag = "\\s*(f)\\s*";
const string ParserSort::regexInstructionSort = "(sort)";


ParserSort::ParserSort(ParserBase* _nextParser) : ParserBase(_nextParser) {
}

bool ParserSort::tryParse(string userCommand, PARSED_COMMAND& parsedCommand) {
	
	string instruction;
	string arguments;
	getInstructionAndArguments(userCommand, instruction, arguments);
	if (!checkInstruction(instruction)) {
		return false;
	}

	parseSort(parsedCommand, arguments);

	return true;
}

bool ParserSort::getInstructionAndArguments(const string& userCommand, 
										string& instruction, 
										string& arguments) {
	regex sortFormat(regexInstructionAndArguments);
	smatch matchResults;

	if (!regex_match(userCommand, matchResults, sortFormat)) {

		return false;
	}

	assert(matchResults.size() > ARGUMENTS_POS);
	instruction = matchResults[INSTRUCTION_POS];
	arguments = matchResults[ARGUMENTS_POS];
	

	return true;
}

bool ParserSort::checkInstruction(const string& instruction) {
	if (regex_match(instruction, regex(regexInstructionSort,
									   tr1::regex_constants::icase))) {
		return true;
	}

	return false;
}

void ParserSort::parseSort(PARSED_COMMAND& parsedCommand,
				  const string& arguments) {
	smatch matchingResults;

	if (regex_match(arguments, matchingResults, regex(regexArgumentSortAlphabet))) {
		parsedCommand.commandType = SORT_ALPHABET;
	}else if (regex_match(arguments, matchingResults, regex(regexArgumentSortCompleted))) {
		parsedCommand.commandType = SORT_COMPLETED;
	}else if (regex_match(arguments, matchingResults, regex(regexArgumentSortFlag))) {
		parsedCommand.commandType = SORT_FLAG;
	}else if (regex_match(arguments, matchingResults, regex(regexArgumentSortTime))) {
		parsedCommand.commandType = SORT_TIME;
	}else {
		parsedCommand.commandType = INVALID;
		parsedCommand.errorType = parsedCommand.ERROR_FORMAT_SORT;
	}
}

